import React, { PureComponent } from "react";
import store from "./store";
import { ADDCOUNT,ADDCOUNTASYNC, MiNUSCOUNT, ADDREGISTER } from "./store/actions";

export default class ReduxBaseDemo extends PureComponent {
  state = {
    count: store.getState().count,
    registerList: store.getState().registerList,
  };

  componentDidMount() {
    //订阅仓库中状态的变化：当仓库中的状态发生变化后，就会调用回调函数
    store.subscribe(() => {
      console.log("仓库的状态发生变化");
      console.log("store.getState()", store.getState());
      this.setState({
        count: store.getState().count,
        registerList: store.getState().registerList,
      });
    });
  }

  addCount = () => {
    store.dispatch(ADDCOUNT(2));
  };

  addCountAsync=()=>{
    store.dispatch(ADDCOUNTASYNC());
  }

  minusCount = () => {
    store.dispatch(MiNUSCOUNT(1));
  };

  addReg = () => {
    store.dispatch(
      ADDREGISTER({
        id: "2023102301003",
        deptName: "内科",
        name: "屈帅",
      })
    );
  };

  render() {
    console.log("render");
    return (
      <div>
        <h1>redux的使用：提取reducer</h1>
        <p>基本类型的数据：</p>
        <p>count:{this.state.count}</p>
        <input type="button" value="加法" onClick={this.addCount} />
        <input type="button" value="加法(带异步)" onClick={this.addCountAsync} />
        <input type="button" value="减法" onClick={this.minusCount} />
        <hr />
        <p>引用类型的数据：挂号信息</p>
        <table border="1" width="500">
          <tbody>
            <tr>
              <td>编号</td>
              <td>科室</td>
              <td>姓名</td>
            </tr>
            {this.state.registerList.map((item) => (
              <tr>
                <td>{item.id}</td>
                <td>{item.deptName}</td>
                <td>{item.name}</td>
              </tr>
            ))}
          </tbody>
        </table>
        {/* 添加挂号信息 */}
        <div>
          <input type="button" value="添加" onClick={this.addReg} />
        </div>
      </div>
    );
  }
}

